package com.example.smart.widget

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Space
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import com.example.lib.extend.dip2px
import com.example.smart.R

/**
 * 指示器视图
 */
class ViewPagerIndicatorView(
    context: Context,
    attrs: AttributeSet
) : LinearLayout(context, attrs) {

    val imgArray = ArrayList<ImageView>()

    var selectPos = 0

    private var selectDrawable: Drawable

    private var unSelectDrawable: Drawable

    init {
        orientation = HORIZONTAL
        selectDrawable = ContextCompat.getDrawable(getContext(), com.example.lib.R.drawable.round_0a0b35)!!
        unSelectDrawable = ContextCompat.getDrawable(getContext(), R.drawable.round_d8d8d8_6)!!
    }

    fun addIndicator(content: Int) {
        removeAllViews()
        imgArray.clear()
        selectPos = 0
        for (index in 0 until content) {
            val indicator = ImageView(context)
            val imgParams = LayoutParams(
                context.dip2px(6f), context.dip2px(6f)
            )
            indicator.setImageDrawable(unSelectDrawable)
            imgArray.add(indicator)
            addView(indicator, imgParams)
            if (index != content - 1) {
                val space = Space(context)
                val spaceParams = LayoutParams(
                    context.dip2px(5f), ViewGroup.LayoutParams.WRAP_CONTENT
                )
                addView(space, spaceParams)
            }
        }

        setSelectIndicator(selectPos)
    }

    fun setSelectIndicator(selectPos: Int) {
        if (imgArray.isNotEmpty() && selectPos < imgArray.size) {
            val imgParams = LayoutParams(
                context.dip2px(6f), context.dip2px(6f)
            )

            imgArray[this.selectPos].setImageDrawable(unSelectDrawable)
            imgArray[this.selectPos].layoutParams = imgParams
            imgArray[this.selectPos].requestLayout()

            imgArray[selectPos].setImageDrawable(selectDrawable)
            imgArray[selectPos].layoutParams = imgParams
            imgArray[selectPos].requestLayout()

            this.selectPos = selectPos
        }
    }


    fun setSelectDrawable(@DrawableRes id: Int) {
        selectDrawable = ContextCompat.getDrawable(context, id)!!
    }

    fun setUnSelectDrawable(@DrawableRes id: Int) {
        unSelectDrawable = ContextCompat.getDrawable(context, id)!!
    }
}